﻿using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;

namespace BootstrapBlazorApp.Shared.Shared;

public class JwtAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly ILocalStorageService _storage;

    public JwtAuthenticationStateProvider(ILocalStorageService service) => _storage = service;

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var accessToken = await _storage.GetItemAsStringAsync(ClientAppKey.AccessToken);
        var refreshToken = await _storage.GetItemAsStringAsync(ClientAppKey.RefreshToken);
        return new AuthenticationState(TokenHelper.GetClaimsPrincipal(accessToken, refreshToken));
    }

    /// <summary>
    /// 更新授权信息
    /// </summary>
    /// <param name="accessToken">授权账票</param>
    /// <param name="refreshToken">刷新账票</param>
    /// <param name="notify">是否推送通知</param>
    /// <returns></returns>
    public async Task UpdateAuthenticated(string? accessToken, string? refreshToken, bool notify = true)
    {
        var user = TokenHelper.GetClaimsPrincipal(accessToken, refreshToken);
        if (user.Identity?.IsAuthenticated == true)
        {
            await _storage.SetItemAsStringAsync(ClientAppKey.AccessToken, accessToken);
            await _storage.SetItemAsStringAsync(ClientAppKey.RefreshToken, refreshToken);
        }
        else
        {
            await _storage.RemoveItemAsync(ClientAppKey.AccessToken);
            await _storage.RemoveItemAsync(ClientAppKey.RefreshToken);
        }
        var authentication = new AuthenticationState(user);

        //通知推送
        if (notify)
        {
            NotifyAuthenticationStateChanged(Task.FromResult(authentication));
        }
    }
}
